package com.lanelu.hencoderplusstudy.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View
import com.lanelu.hencoderplusstudy.R

private val IMAGE_WIDTH = 200f.dp
private val IMAGE_WIDTH2 = 220f.dp
private val IMAGE_PADDING = 20f.dp
private val XFERMODE = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)

/**
 * 自定义圆形头像
 */
class AvatarView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG);
    private val bounds = RectF(
        IMAGE_PADDING,
        IMAGE_PADDING,
        IMAGE_PADDING + IMAGE_WIDTH2,
        IMAGE_PADDING + IMAGE_WIDTH2
    )

    private val circleBitmap =
        Bitmap.createBitmap(IMAGE_WIDTH2.toInt(), IMAGE_WIDTH2.toInt(), Bitmap.Config.ARGB_8888)

    private val avatarBitmap =
        Bitmap.createBitmap(IMAGE_WIDTH2.toInt(), IMAGE_WIDTH2.toInt(), Bitmap.Config.ARGB_8888)

    init {
        val canvas = Canvas(circleBitmap)
        paint.color = Color.parseColor("#000000");
        canvas.drawOval(
            0f.dp,
            0f.dp,
            IMAGE_WIDTH2,
            IMAGE_WIDTH2,
            paint
        )

        canvas.setBitmap(avatarBitmap)
        paint.color = Color.parseColor("#FF0000");
        canvas.drawOval(
            (IMAGE_WIDTH2 - IMAGE_WIDTH) / 2,
            (IMAGE_WIDTH2 - IMAGE_WIDTH) / 2,
            (IMAGE_WIDTH2 + IMAGE_WIDTH) / 2,
            (IMAGE_WIDTH2 + IMAGE_WIDTH) / 2,
            paint
        )
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val count = canvas.saveLayer(bounds, null)//设置离屏缓冲
        canvas.drawBitmap(circleBitmap, IMAGE_PADDING, IMAGE_PADDING, paint)
        paint.xfermode = XFERMODE
        canvas.drawBitmap(
            getAvatar(IMAGE_WIDTH2.toInt(), R.drawable.ic_avatar),
            IMAGE_PADDING,
            IMAGE_PADDING,
            paint
        )
        paint.xfermode = null
        canvas.restoreToCount(count)

        canvas.save()
        paint.color = Color.BLACK
        paint.strokeWidth = 5f.dp
        paint.style = Paint.Style.STROKE
        canvas.drawOval(
            IMAGE_PADDING,
            IMAGE_PADDING,
            IMAGE_PADDING + circleBitmap.width,
            IMAGE_PADDING + circleBitmap.height,
            paint
        )
        canvas.restore()


    }

    private fun getAvatar(width: Int, resourceId: Int): Bitmap {
        val options = BitmapFactory.Options()
        options.inJustDecodeBounds = true//第一次只是获取图片尺寸
        BitmapFactory.decodeResource(resources, resourceId, options)//先读取一次图片尺寸
        options.inJustDecodeBounds = false//第二次需要完整的读取图片
        options.inDensity = options.outWidth//图片原先尺寸
        options.inTargetDensity = width//图片目标尺寸
        return BitmapFactory.decodeResource(resources, resourceId, options)
    }

}